module top_ctrl (
    input clk,
    input rst,
    input [3:0] key_row,
    input [1:0] m,
    input key_sel,
    input [15:0] rom_data,
    output [3:0] key_col,
    output [7:0] seg,
    output [2:0] sel,
    output reg [7:0] pc
);

  wire [3:0] val;
  wire is_pressed;

  key u_key (
      clk,
      rst,
      key_row,
      key_col,
      val,
      is_pressed
  );

  display u_display (
      clk,
      rst,
      {rom_data, 8'h0, pc},
      8'b11001111,
      seg,
      sel
  );

  reg [16:0] cnt;
  localparam CNT_MAX = 17'd99_999;

  always @(posedge clk or negedge rst) begin
    if (!rst) begin
      cnt <= 17'd0;
    end else if (cnt == CNT_MAX) begin
      cnt <= 17'd0;
    end else begin
      cnt <= cnt + 17'd1;
    end
  end

  always @(posedge clk or negedge rst) begin
    if (!rst) begin
      pc <= 8'd0;
    end else begin
      case (m)
        2'b00: begin
          pc <= 8'd0;
        end
        2'b01: begin
          if (cnt == CNT_MAX) begin
            pc <= pc + 8'd1;
          end else begin
            pc <= pc;
          end
        end
        2'b10: begin
          if (cnt == CNT_MAX) begin
            pc <= pc - 8'd1;
          end else begin
            pc <= pc;
          end
        end
        2'b11: begin
          if (is_pressed) begin
            case (key_sel)
              2'b0: begin
                pc[7:4] <= val;
              end
              2'b1: begin
                pc[3:0] <= val;
              end
            endcase
          end
        end
      endcase
    end
  end

endmodule
